package com.ihighest.app.infox.activity;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient.ErrorCode;
import io.rong.imlib.RongIMClient.ResultCallback;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.MessageContent;
import io.rong.message.ImageMessage;
import io.rong.message.TextMessage;
import io.rong.message.VoiceMessage;

import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.core.Application;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.im.IssueMessage;

/**
 * 融云聊天界面
 * 
 * @author lkx Created at 2015-10-12 下午2:51:00
 * @version 1.0
 */
public class ConversationActivity extends FragmentActivity {
	private TextView groupName;
	/**
	 * 目标 Id
	 */
	private String mTargetId;

	/**
	 * 刚刚创建完讨论组后获得讨论组的id 为targetIds，需要根据 为targetIds 获取 targetId
	 */
	private String mTargetIds;

	/**
	 * 会话类型
	 */
	private Conversation.ConversationType mConversationType;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		Application.getInstance().addActivity(this);
		Const.IS_CHAT = true;
		if (!Const.IS_RONGIM_INIT) {
			AppKit.connectRongIM(ConversationActivity.this,
					SharedPreferencesKit.getString(ConversationActivity.this, Const.SP_KEY_USER_RTOKEN));
		}
		setContentView(R.layout.infox_activity_conversation);
		Intent intent = getIntent();
		getIntentDate(intent);
		initView();
	}

	private void initView() {
		groupName = (TextView) findViewById(R.id.groupName);
		findViewById(R.id.clooseChart).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Const.IS_CHAT = false;
				finish();
			}
		});
		groupName.setText(getIntent().getData().getQueryParameter("title"));
		boolean flg = true;
		if (!TextUtils.isEmpty(Const.IM_EXTRA) && flg) {
			final String[] extraArr = Const.IM_EXTRA.split(":");
			RongIM.getInstance().getRongIMClient().clearMessages(mConversationType, mTargetId, new ResultCallback<Boolean>() {

				@Override
				public void onError(ErrorCode arg0) {

				}

				@SuppressWarnings("deprecation")
				@Override
				public void onSuccess(Boolean arg0) {
					if (arg0) {

						if (extraArr[0].contains("issue")) {
							Api.get("qa/issueDetail", ApiParam.create().addParam("id", extraArr[1]), new ApiCallback(
									ConversationActivity.this, true) {

								@Override
								public void handleSuccess(final ApiResult result) {
									try {
										if (result.getCode() == 100) {

											JSONObject jsonObject = new JSONObject();
											if (result.getData().has("content")) {
												jsonObject.put("text", result.getData().getString("content"));
											}
											if (result.getData().has("area")) {
												jsonObject.put("area", result.getData().getString("area"));
											}
											if (result.getData().has("name")) {
												jsonObject.put("crop", result.getData().getString("name"));
											}
											if (result.getData().has("weather")) {
												jsonObject.put("weather", result.getData().getString("weather"));
											}
											if (result.getData().has("measure")) {
												jsonObject.put("manure", result.getData().getString("measure"));
											}
											if (result.getData().has("gold") && result.getData().getInt("gold") > 0) {
												jsonObject.put("gold", result.getData().getString("gold"));
											}
											if (result.getData().has("voice")) {
												jsonObject.put("voiceUri", result.getData().getString("voice"));
											}
											if (result.getData().has("images") && result.getData().getJSONArray("images").length() > 0) {
												jsonObject.put("imageUrls", result.getData().getJSONArray("images"));
											}

											RongIM.getInstance()
													.getRongIMClient()
													.insertMessage(mConversationType, mTargetId, result.getData().getString("rid"),
															IssueMessage.obtain(jsonObject));

											/*
											 * if
											 * (result.getData().has("content")
											 * &&
											 * !TextUtils.isEmpty(result.getData
											 * ().getString("content"))) {
											 * 
											 * TextMessage tm =
											 * TextMessage.obtain("问题：" +
											 * result.
											 * getData().getString("content"));
											 * RongIM
											 * .getInstance().getRongIMClient()
											 * .insertMessage(mConversationType,
											 * mTargetId,
											 * result.getData().getString
											 * ("rid"), tm); } String info = "";
											 * if (result.getData().has("area")
											 * &&
											 * !TextUtils.isEmpty(result.getData
											 * ().getString("area"))) { info +=
											 * "地区：" +
											 * result.getData().getString
											 * ("area") + "\n"; } if
											 * (result.getData().has("name") &&
											 * !
											 * TextUtils.isEmpty(result.getData(
											 * ).getString("name"))) { info +=
											 * "作物：" +
											 * result.getData().getString
											 * ("name") + "\n"; } if
											 * (result.getData().has("weather")
											 * &&
											 * !TextUtils.isEmpty(result.getData
											 * ().getString("weather"))) { info
											 * += "天气：" +
											 * result.getData().getString
											 * ("weather") + "\n"; } if
											 * (result.getData().has("measure")
											 * &&
											 * !TextUtils.isEmpty(result.getData
											 * ().getString("measure"))) { info
											 * += "药、肥：" +
											 * result.getData().getString
											 * ("measure") + "\n"; } if
											 * (result.getData().has("gold") &&
											 * result.getData().getInt("gold")
											 * != 0) { info += "悬赏：" +
											 * result.getData().getInt("gold") +
											 * "个金币" + "\n"; } if
											 * (!TextUtils.isEmpty(info)) {
											 * TextMessage tm =
											 * TextMessage.obtain(info);
											 * RongIM.getInstance
											 * ().getRongIMClient()
											 * .insertMessage(mConversationType,
											 * mTargetId,
											 * result.getData().getString
											 * ("rid"), tm); } if
											 * (result.getData().has("voice") &&
											 * !
											 * TextUtils.isEmpty(result.getData(
											 * ).getString("voice"))) { new
											 * HttpUtils
											 * ().download(result.getData
											 * ().getString("voice"),
											 * File.createTempFile("infpx-tmp",
											 * "amr").getAbsolutePath(), new
											 * RequestCallBack<File>() {
											 * 
											 * @Override public void
											 * onFailure(HttpException arg0,
											 * String arg1) {
											 * 
											 * }
											 * 
											 * @Override public void
											 * onSuccess(ResponseInfo<File>
											 * arg0) { try { int length =
											 * AppKit.
											 * getAmrDuration(arg0.result);
											 * VoiceMessage vm =
											 * VoiceMessage.obtain(
											 * Uri.parse(arg0
											 * .result.getAbsolutePath()),
											 * length); RongIM.getInstance()
											 * .getRongIMClient()
											 * .insertMessage(mConversationType,
											 * mTargetId,
											 * result.getData().getString
											 * ("rid"), vm); } catch (Exception
											 * e) { e.printStackTrace(); } }
											 * 
											 * }); }
											 * 
											 * if
											 * (result.getData().has("images")
											 * && result.getData().getJSONArray(
											 * "images") != null &&
											 * result.getData
											 * ().getJSONArray("images"
											 * ).length() > 0) { for (int i = 0;
											 * i <
											 * result.getData().getJSONArray(
											 * "images").length(); i++) { String
											 * url =
											 * result.getData().getJSONArray
											 * ("images").getString(i); new
											 * HttpUtils().download(url,
											 * File.createTempFile("infpx-tmp",
											 * url
											 * .substring(url.lastIndexOf(".")))
											 * .getAbsolutePath(), new
											 * RequestCallBack<File>() {
											 * 
											 * @Override public void
											 * onFailure(HttpException arg0,
											 * String arg1) {
											 * 
											 * }
											 * 
											 * @Override public void
											 * onSuccess(ResponseInfo<File>
											 * arg0) { try { ImageMessage im =
											 * ImageMessage.obtain(
											 * Uri.parse("file://" +
											 * arg0.result.getAbsolutePath()),
											 * Uri.parse("file://" +
											 * arg0.result.getAbsolutePath()),
											 * true); RongIM.getInstance()
											 * .getRongIMClient()
											 * .insertMessage(mConversationType,
											 * mTargetId,
											 * result.getData().getString
											 * ("rid"), im); } catch (Exception
											 * e) { e.printStackTrace(); } }
											 * 
											 * }); } }
											 */

											Api.get("chat/history",
													ApiParam.create().addParam("page", 1).addParam("size", Integer.MAX_VALUE - 1)
															.addParam("bid", extraArr[1]).addParam("tmid", extraArr[2]), new ApiCallback(
															ConversationActivity.this, true) {
														@Override
														public void handleSuccess(ApiResult result) {
															if (result.getCode() == 100) {
																JSONArray array = result.getDatas();
																if (array.length() == 0) {
																	return;
																}
																JSONObject json = null;
																MessageContent mc = null;
																for (int i = array.length() - 1; i >= 0; i--) {
																	try {
																		json = array.getJSONObject(i);
																		if ("RC:TxtMsg".equalsIgnoreCase(json.getString("objectName"))) {
																			mc = TextMessage.obtain(new JSONObject(json
																					.getString("content")).getString("content"));
																		} else if ("RC:VcMsg".equalsIgnoreCase(json.getString("objectName"))) {
																			String base64 = new JSONObject(json.getString("content"))
																					.getString("content");
																			byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
																			mc = VoiceMessage.obtain(Uri.parse(AppKit.getFileFromBytes(
																					bytes).getAbsolutePath()),
																					new JSONObject(json.getString("content"))
																							.getInt("duration"));
																		} else if ("RC:ImgMsg".equalsIgnoreCase(json
																				.getString("objectName"))) {
																			String base64 = new JSONObject(json.getString("content"))
																					.getString("content");
																			byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
																			mc = ImageMessage.obtain(
																					Uri.parse("file://"
																							+ AppKit.getFileFromBytes(bytes)
																									.getAbsolutePath()),
																					Uri.parse("file://"
																							+ AppKit.getFileFromBytes(bytes)
																									.getAbsolutePath()), true);
																		}
																		RongIM.getInstance().getRongIMClient()
																				.insertMessage(mConversationType,
																				// json.getString("toUserId"),
																						mTargetId, json.getString("fromUserId"), mc);
																		// int
																		// cid =
																		// mConversationType
																		// ==
																		// ConversationType.PRIVATE
																		// ? 1 :
																		// -1;
																		// if
																		// (cid
																		// ==
																		// -1) {
																		// cid =
																		// mConversationType
																		// ==
																		// ConversationType.GROUP
																		// ? 3 :
																		// -1;
																		// }
																		// int
																		// md =
																		// mTargetId.equalsIgnoreCase(json.getString("toUserId"))
																		// ? 2
																		// : 1;
																		// if
																		// (cid
																		// !=
																		// -1) {
																		// AppKit.writeRongIMMessage(mContext,
																		// cid,
																		// md,
																		// json.getString("fromUserId"),
																		// json.getString("toUserId"),
																		// json.getString("content"),
																		// json.getString("objectName"),
																		// json.getLong("timestamp"));
																		// }
																	} catch (JSONException e) {
																		e.printStackTrace();
																	}
																}
															}
														}

														@Override
														public void handleFailure(Exception e, String msg) {

														}
													}, ConversationActivity.this);
										}

									} catch (Exception e1) {
										e1.printStackTrace();
									}

								}

								@Override
								public void handleFailure(Exception e, String msg) {

								}
							}, ConversationActivity.this);

						}

					}
				}

			});
		}
	}

	/**
	 * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
	 */
	private void getIntentDate(Intent intent) {

		mTargetId = intent.getData().getQueryParameter("targetId");
		mTargetIds = intent.getData().getQueryParameter("targetIds");
		// intent.getData().getLastPathSegment();//获得当前会话类型
		mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));

		enterFragment(mConversationType, mTargetId);
	}

	//
	/**
	 * 加载会话页面 ConversationFragment
	 * 
	 * @param mConversationType
	 *            会话类型
	 * @param mTargetId
	 *            目标 Id
	 */
	private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

		ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);
		Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon().appendPath("conversation")
				.appendPath(mConversationType.getName().toLowerCase(Locale.getDefault())).appendQueryParameter("targetId", mTargetId)
				.build();

		fragment.setUri(uri);
	}

}
